package cn.hhy.org.service.impl;

import cn.hhy.org.domain.Department;
import cn.hhy.org.mapper.DepartmentMapper;
import cn.hhy.org.service.IDepartmentService;
import cn.hhy.org.query.DepartmentQuery;
import cn.hhy.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Transactional(readOnly = true ,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public void save(Department department) {

        departmentMapper.save(department);
        update(department);
    }

    @Override
    public void update(Department department) {

        if(department.getParent()==null){
            department.setDirPath("/"+department.getId());
        }else {
            /** 获取上级部门的dirPath */
            Department parent = departmentMapper.loadById(department.getParent().getId());
            department.setDirPath(parent.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);

    }

    @Override
    public void delete(Long id) {
        departmentMapper.delete(id);

    }

    @Override
    public Department loadById(Long id) {
        return departmentMapper.loadById(id);
    }

    @Override
    public QueryResult<Department> loadAll(DepartmentQuery departmentQuery) {
        Long departmentCountByQuery = departmentMapper.findDepartmentCountByQuery(departmentQuery);
        List<Department> departmentByQuery = departmentMapper.loadAll(departmentQuery);
        return new QueryResult<Department>(departmentCountByQuery,departmentByQuery);
    }

    @Override
    public List<Department> treeData() {
        //查出所有pid=0的顶级节点
        List<Department> sonsByPid = departmentMapper.findSonsByPid((long) 0);
        for (Department department : sonsByPid) {
            List<Department> byPid = findByPid(department.getId());
            department.setChildren(byPid);
        }
        return sonsByPid;
    }
    //通过父级ID找它的所有子级节点(查询所有儿子)
    private List<Department> findByPid(Long pid) {
        List<Department> sonList = departmentMapper.findSonsByPid(pid);
        //你爸 的 所有儿子
        for (Department department : sonList) {
            List<Department> byPid = findByPid(department.getId());
            department.setChildren(byPid);
        }
        return sonList;
    }

    @Override
    public void PatchDelete(Long[] ids) {
        departmentMapper.PatchDelete(ids);
    }

    @Override
    public List<Department> loadAll2() {
        return departmentMapper.loadAll2();
    }
}
